package com.ucombuy.user.controller;

import com.alibaba.fastjson.JSON;
import com.ucombuy.common.util.CookieUtil;
import com.ucombuy.common.vo.Const;
import com.ucombuy.common.vo.ResponseCode;
import com.ucombuy.common.vo.ServerResponse;
import com.ucombuy.user.pojo.User;
import com.ucombuy.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by yaosheng on 2021/3/15.
 */
@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/login.do")
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session, HttpServletResponse httpServletResponse){

        ServerResponse<User> response = iUserService.login(username,password);
        if(response.isSuccess()){
            CookieUtil.writeLoginToken(httpServletResponse,session.getId());
            redisTemplate.opsForValue ().set (session.getId (),JSON.toJSONString (response.getData ()),Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
        }
        return response;
    }

    @PostMapping("/logout.do")
    @ResponseBody
    public ServerResponse<String> logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){

        String loginToken = CookieUtil.readLoginToken (httpServletRequest);
        CookieUtil.delLoginToken (httpServletRequest,httpServletResponse);
        assert loginToken != null;
        redisTemplate.opsForHash ().delete (loginToken);
        return ServerResponse.creatBySuccess ();
    }

    @PostMapping("/register.do")
    @ResponseBody
    public ServerResponse<String> register(User user){
        return iUserService.register (user);
    }

    @PostMapping("check_valid.do")
    @ResponseBody
    public ServerResponse<String> checkValid(String str,String type){
        return iUserService.checkVaild(str, type);
    }

    @PostMapping("get_user_info.do")
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpServletRequest httpServletRequest){

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if(StringUtils.isEmpty(loginToken)){
            return ServerResponse.creatByErrorMessage("用户未登录，无法获取当前用户信息");
        }
        String userJsonStr = redisTemplate.opsForValue ().get (loginToken);
        User user = JSON.parseObject (userJsonStr,User.class);

        if(user !=null){
            return ServerResponse.creatBySuccess(user);
        }
        return ServerResponse.creatByErrorMessage("用户未登录，无法获取当前用户信息");
    }

    @PostMapping("forget_get_question.do")
    @ResponseBody
    public ServerResponse<String> forgetQuestion(String username){
        return iUserService.selectQuestion(username);
    }

    @PostMapping("forget_check_answer.do")
    @ResponseBody
    public ServerResponse<String> forgetAnswer(String username,String question,String answer){
        return iUserService.checkAnswer(username,question,answer);
    }

    @PostMapping("forget_rest_password.do")
    @ResponseBody
    public ServerResponse<String> forgetRestPassword(String username,String passwordNew,String forgetToken){
        return iUserService.forgetResetPassword(username,passwordNew,forgetToken);
    }

    @PostMapping("reset_password.do")
    @ResponseBody
    public ServerResponse<String> resetPassword(HttpServletRequest httpServletRequest, String passwordOld, String passwordNew){

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if(StringUtils.isEmpty(loginToken)){
            return ServerResponse.creatByErrorMessage("用户未登录，无法获取当前用户信息");
        }
        String userJsonStr = redisTemplate.opsForValue ().get (loginToken);
        User user = JSON.parseObject (userJsonStr,User.class);

        if(user == null){
            return ServerResponse.creatByErrorMessage("用户未登录");
        }
        return iUserService.resetPassword(passwordOld,user,passwordNew);
    }

    @PostMapping("update_information.do")
    @ResponseBody
    public ServerResponse<User> update_information(HttpServletRequest httpServletRequest,User user){

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if(StringUtils.isEmpty(loginToken)){
            return ServerResponse.creatByErrorMessage("用户未登录，无法获取当前用户信息");
        }
        String userJsonStr = redisTemplate.opsForValue ().get (loginToken);;
        User currentUser = JSON.parseObject (userJsonStr,User.class);

        if(currentUser == null){
            return ServerResponse.creatByErrorMessage("用户未登录");
        }
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());
        ServerResponse<User> response = iUserService.updateInformation(user);
        if(response.isSuccess()){
            redisTemplate.opsForHash ().put (loginToken, JSON.toJSONString (response.getData()),Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
        }
        return response;
    }

    @PostMapping("get_information.do")
    @ResponseBody
    public ServerResponse<User> get_information(HttpServletRequest httpServletRequest){

        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if(StringUtils.isEmpty(loginToken)){
            return ServerResponse.creatByErrorMessage("用户未登录，无法获取当前用户信息");
        }
        String userJsonStr = redisTemplate.opsForValue ().get (loginToken);
        User currentUser = JSON.parseObject (userJsonStr,User.class);

        if(currentUser == null){
            return ServerResponse.creatByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"未登录，需要强制登陆status=10");
        }
        return iUserService.getInformation(currentUser.getId());
    }
}
